<template>
  <div>
    <!-- 模糊查询 -->
    <el-card style="height: 80px;">
      <el-form :inline="true" :model="searchForm" ref="ruleForm" class="demo-form-inline">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="searchForm.username" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input v-model="searchForm.level" placeholder="等级"></el-input>
        </el-form-item>
        <el-form-item label="注册时间" prop="createdAt1">
          <el-date-picker style="width: 180px" v-model="searchForm.createdAt1" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>_
        <el-form-item prop="createdAt2">
          <el-date-picker style="width: 180px" v-model="searchForm.createdAt2" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="onSubmit">查询</el-button>
          <el-button type="warning" size="small" @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 分页查询表格 -->
    <el-card style="height: 525px;margin-top: 5px;">
      <div>
        <el-button size="small" type="danger" @click="deleteBatch" icon="el-icon-minus">批量删除</el-button>
        <el-button size="small" type="primary" @click="handleAdd" icon="el-icon-plus">添加</el-button>
        <!--导入导出按钮-->
        <el-button size="small" type="success" @click="uploadExcelDialog = true" icon="el-icon-upload">导入</el-button>
      </div>
      <!--添加/更新弹出对话框-->
      <!--表单校验需要设置
            1.需要在el-form中设置rules，ref属性
            2.需要在el-form-item设置prop属性
            3.需要在data中设置rules属性其中的key是prop的值-->
      <el-dialog :title="title" style="margin-left: 300px; width: 1000px;" :visible.sync="editUserDialog" :close-on-click-modal="false">
        <el-form :model="editUser" label-width="70px" :rules="rules" ref="editUser">
          <el-form-item label="用户名" prop="username">
            <el-input size="small" style="width: 300px;" v-model="editUser.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input show-password size="small" style="width: 300px;" v-model="editUser.password"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input size="small" style="width: 300px;" v-model="editUser.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input size="small" style="width: 300px;" v-model="editUser.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="等级">
            <el-input size="small" style="width: 300px;" v-model="editUser.level" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="积分">
            <el-input size="small" style="width: 300px;" v-model="editUser.points" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker v-model="editUser.createdAt" type="date" placeholder="选择日期"> </el-date-picker>
          </el-form-item>
          <!-- 添加头像上传 -->
          <el-form-item label="头像" prop="avatar">
            <el-upload
              class="AvatarUpload"
              action=""
              :http-request="uploadFile"
              :on-change="handleChange"
              :limit="1"
              accept=".jpg,.jpeg,.png"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

            <!-- 显示预览头像 -->
            <div v-if="editUser.avatar" class="avatar-preview" style="margin-top: 20px;">
              <img :src="editUser.avatar" alt="预览头像" style="width: 80px; height: 80px"/>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-top: 0px">
          <el-button @click="resetEditForm('editUser')" size="small">取 消</el-button>
          <el-button type="primary" @click="saveUser('editUser')" size="small">确 定</el-button>
        </div>
      </el-dialog>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="100">
        </el-table-column>
        <el-table-column prop="password" label="密码" width="100">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="100">
        </el-table-column>
        <el-table-column prop="phone" label="手机" width="100">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100">
        </el-table-column>
        <el-table-column prop="level" label="等级" width="100">
        </el-table-column>
        <el-table-column prop="createdAt" label="日期" width="100">
        </el-table-column>
        <el-table-column prop="attel" label="属性" width="100">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; align-items: center;margin-top: 10px;">
        <!-- 分页 -->
        <el-pagination background
          style="display: flex;align-items: center;margin-top: 5px;margin-left: 400px; display: inline;"
          @size-change="handleSizeChange" :page-sizes="pageSizes" @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum" :page-size="searchForm.pageSize"
          layout="total, sizes, prev,pager, next, jumper" :total="total">
        </el-pagination>
        <!-- 分页跳转按钮 -->
        <el-button size="small" type="primary" @click="toPage" style="margin-right: 50px;">跳转</el-button>
      </div>
    </el-card>
    <!--上传excel弹窗-->
    <!--弹窗区域-->
    <el-dialog
      title="上传计量单位数据"
      width="26%"
      :visible.sync="uploadExcelDialog"
      :close-on-click-modal="false"
    >
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="uploadExcelFun"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>
        <el-button type="primary" @click="">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { findAll2, deleteOne, batchdelete, addUser, updateUser ,uploadExcel} from "@/api/user/user"
import { title } from "@/settings";
import { uploadImage } from '@/api/user/user'
export default {
  name: "user",
  data() {
    //自定义手机号规则
    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else {
        const reg = /^\d{11}$/
        if (reg.test(value)) {
          callback();
        } else
          callback(new Error('请输入11位的手机号'));
      }
    };
    return {
      pageSizes: [3, 6, 9],
      title:"添加用户",
      searchForm: {
        id: null,
        username: null,
        level: null,
        createdAt1: null,
        createdAt2: null,
        avatar: null,
        pageNum: 1,//当前页码
        pageSize: 3,//每页条数
      },
      file: null,
      fileList: [],
      uploadExcelDialog:false,
      editUser: {},
      multipleSelection: [],
      tableData: [],
      total: 0,
      editUserDialog: false,
      excelDialogVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    async saveUser(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          // 表单校验通过需要进一步判断是添加用户还是修改用户
          if (this.title === "添加用户") {
            addUser(this.editUser).then(res => {
              if (res.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '添加成功',
                  duration: 1000
                });
                this.searchForm.pageNum = 1,
                  this.findAll2();
                this.editUser = {};
                this.$refs[formName].resetFields();
              } else {
                this.$message({
                  type: 'error',
                  message: '添加失败',
                  duration: 1000
                });
              }
            })
          } else {
            updateUser(this.editUser).then(res => {
              if (res.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '修改成功',
                  duration: 1000
                });
                this.searchForm.pageNum = 1,
                  this.findAll2();
                this.editUser = {};
                this.$refs[formName].resetFields();
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败',
                  duration: 1000
                });
              }
            })
          }
          this.editUserDialog = false;
        } else {
          // 表单校验未通过
          this.$message({
            type: 'error',
            message: '表单校验失败',
            duration: 1000
          });
          return false;
        }
      });
    },
    // 上传头像
    uploadFile() {
      const file = this.file;
      if (!file) {
        this.$message.error("请选择一个文件");
        return;
      }
      // 执行修改用户之前，检查头像是否有变化，如果有变化，则需要上传头像
      if (this.editUser.avatar !== this.searchForm.avatar) {
        const formData = new FormData();
        formData.append('file', file);
        uploadImage(formData).then((res) => {
          this.$message({
            message: "上传成功",
            type: "success",
          });
          this.editUser.avatar = res.data
          console.log("fileSrc", this.editUser.avatar)
        }).catch((error) => {
          this.$message.error("上传失败");
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.findAll2();
    },
    onSubmit() {
      this.findAll2();
    },
    findAll2() {
      findAll2(this.searchForm).then(res => {
        this.tableData = res.data.list;
        this.total = res.data.total;
      })
    },
    //分页
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.findAll2()
    },
    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.findAll2()
    },
    toPage() {
      this.findAll2();
    },
    resetFields(formName) {
      this.$refs[formName].resetFields();
    },
    //修改
    handleEdit(index, row) {
      this.title = "修改用户";
      // 数据回显是浅拷贝，所以修改数据后需要重新赋值，使用深拷贝
      this.editUser = JSON.parse(JSON.stringify(row));
      this.editUserDialog = true
      this.resetFields('editUser')
    },
    // 添加
    handleAdd() {
      this.title = "添加用户";
      this.editUser = {};  // 数据回显
      this.editUserDialog = true
      this.resetFields('editUser')
    },
    //删除
    handleDelete(index, row) {
      //console.log(index, row);
      this.$confirm("确认删除该单位吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteOne(row.id).then(res => {
          //console.log('res.code',res.code);
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          }
        })
        //刷新
        this.searchForm.pageNum = 1,
          this.findAll2();
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(searchForm => searchForm.id)
      console.log(this.multipleSelection);
    },
    //批量删除
    deleteBatch() {
      this.$confirm("确认删除该单位吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //console.log(this.multipleSelection);
        batchdelete(this.multipleSelection)
          .then(res => {
            if (res.code === 20000) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            } else {
              this.$message({
                type: 'error',
                message: '删除失败'
              })
            }
          })
        //刷新
        this.searchForm.pageNum = 1,
          this.findAll2();
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },

    resetEditForm(formName) {
      this.editUserDialog = false;
      this.$refs[formName].resetFields();
    },
    // 上传前的回调，用于清空上次上传的文件列表
    beforeUpload(file) {
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      return true;
    },
    uploadExcelFun(){
      const file = this.file;
      // FormData是js对象,用于存储表单数据
      const formData = new FormData();
      formData.append("file", file); // 由后端接口决定,后端参数叫file
      // 封装的上传文件方法
      uploadExcel(formData).then((res) => {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        // 上传成功后添加到文件列表
        this.fileList.push({
          name: file.name,
        }); // 上传成功后添加到文件列表
        this.uploadExcelDialog = false; // 关闭弹窗
        this.pageNum = 1; // 刷新列表
        this.getUnitList(); // 刷新列表
      });
    },
    //监听文件改变
    handleChange(file){
      console.log("file",file)
      this.file = file.raw;
    },
  },
  created() {
    this.findAll2()
  }
}
</script>

<style scoped></style>
